package com.xixi.core.rpc.bootstrap;

import com.xixi.core.rpc.RpcApplication;
import com.xixi.core.rpc.config.RegistryConfig;
import com.xixi.core.rpc.config.RpcConfig;
import com.xixi.core.rpc.model.ServiceMetaInfo;
import com.xixi.core.rpc.model.ServiceRegisterInfo;
import com.xixi.core.rpc.registry.LocalRegistry;
import com.xixi.core.rpc.registry.Registry;
import com.xixi.core.rpc.registry.RegistryFactory;
import com.xixi.core.rpc.server.tcp.VertxTcpServer;

import java.util.List;

/**
 * @author: zxh
 * @date: 2024/8/28 9:41
 * @description: 服务提供者启动
 */
public class ProviderBootstrap {

	/**
	 * 初始化
	 * @author zxh
	 * @param serviceRegisterInfoList 服务注册信息列表
	 */
	public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList) {
		// RPC 框架初始化（配置和注册中心）
		RpcApplication.init();
		// 全局配置
		final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

		// 注册服务
		for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
			String serviceName = serviceRegisterInfo.getServiceName();
			// 本地注册
			LocalRegistry.register(serviceName, serviceRegisterInfo.getImplClass());

			// 服务注册到注册中心
			RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
			Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
			ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
			serviceMetaInfo.setServiceName(serviceName);
			serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
			serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
			try {
				registry.registry(serviceMetaInfo);
			} catch (Exception e) {
				throw new RuntimeException(serviceName + "服务注册失败", e);
			}
		}

		// 启动服务器
		VertxTcpServer vertxTcpServer = new VertxTcpServer();
		vertxTcpServer.doStart(rpcConfig.getServerPort());
	}
}
